package com.srd.phone.application;

import android.app.Activity;

import java.util.Stack;

public class AppActivityManager {
    private static Stack<Activity> activityStack = null;
    private static AppActivityManager screenManager = null;

    public static AppActivityManager getInstance() {
        if (screenManager == null) {
            screenManager = new AppActivityManager();
        }
        return screenManager;
    }

    /**
     * 获得当前栈顶Activity
     *
     * @return
     */
    public Activity currentActivity() {
        if (activityStack == null) {
            return null;
        }
        if (!activityStack.listIterator().hasNext()) {
            return null;
        }
        Activity activity = (Activity) activityStack.lastElement();
        return activity;
    }

    /**
     * 将当前Activity推入栈中
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }


    /**
     * 移除栈中的activity
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (activityStack != null)
            activityStack.remove(activity);
    }


    /**
     * 移除栈中的所有 activity
     */
    public void removeAllActivity(){
        if(activityStack != null){
            for (Activity activity : activityStack){
                activity.finish();
            }

            activityStack.clear();
        }
    }

    /**
     * 退出栈顶Activity
     */
    public void popActivity() {
        if (activityStack != null && activityStack.size() != 0) {
            int size = activityStack.size();
            Activity activity = activityStack.get(size - 1);
            activity.finish();
        }
    }

    /**
     * 退出栈中所有Activity
     */
    public void popAllActivity() {
        if (activityStack == null) {
            return;
        }
        while (true) {
            Activity activity = currentActivity();
            if (activity == null) {
                break;
            }
            removeActivity(activity);
        }
    }

    /**
     * 返回到主界面
     */
    public void backMainActivity() {
        if (activityStack == null) {
            return;
        }
        while (true) {
            Activity activity = currentActivity();
            if (getActivityCount() == 1) {
                break;
            }
            removeActivity(activity);
        }
    }

    /**
     * 获取栈中的activity个数
     *
     * @return
     */
    public int getActivityCount() {
        if (activityStack == null) {
            return -1;
        }
        return activityStack.size();
    }
}
